<template>
  <div class="comment">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="发表（120）评论" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>

    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,index) in comments" :key="index">
        <div
          class="cmt-title"
        >第{{index+1}}楼 用户:{{item.user_name}} 发表时间:{{item.add_time | dataFomat}}</div>
        <div
          class="cmt-body"
        >{{((item.content == 'undefined')||(item.content == ''))?'此用户下落不明':item.content}}</div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="addMore">加载更多</mt-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "",
      pageindex: 1,
      comments: []
    };
  },
  created() {
    this.getComments();
  },
  methods: {
   async getComments() {
     await this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageindex)
        .then(result => {
          if (result.data.status === 0) {
            this.comments = this.comments.concat(result.data.message);
          }
        });
    },
    addMore() {
      this.pageindex++;
      this.getComments();
    },
  async  postComment() {
      // post请求方法
      //1.参数1  请求地址
      //2.参数2  发送的对象
      if (this.msg.trim().length == 0) {
        return;
      }
     await this.$http
        .post("api/postcomment/" + this.id, { content: this.msg.trim() })
        .then(result => {
          if (result.data.status == 0) {
            var cmt = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.msg.trim()
            };
            this.comments.unshift(cmt);
            this.msg = "";
          }
        });
    }
  },
  props: ["id"]
};
</script>

<style scoped>
h3{
    font-size: 18px;
    font-weight: bold;
}
.comment {
  padding: 5px;
}
.cmt-list {
  margin: 10px 0;
}
.cmt-item {
  margin: 5px 0;
  font-size: 13px;
}
.cmt-title {
  background-color: gainsboro;
}
.cmt-body {
  background-color: ghostwhite;
  color: #666;
}
textarea{
    font-size: 12px;
}
</style>


